﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using LdExpress;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    public string ContainerPage = "./Trucker.aspx";
    public string strCondition = "";
    public int NumOfItemsPerPage = 20;
    public string strPager = "";
    public string strIDs = "";
    public string strError = "";
    public string strMess = "";
    public int nPermissions = 0;
    public int nPage = 1;
    public string strPageID = "page_number";
    public string strLetter = "letter";
    public string strAlphaBet = "";
    public string strChar = "";
    public string strExcluded = "ID";
    public string strPartQuery = "";
    protected void Page_Load(object sender, EventArgs e)
    {

        int nPage = 1;
        try
        {

            if (Request.QueryString[strPageID] != null)
                nPage = int.Parse(Request.QueryString[strPageID]);
        }
        catch
        {
            nPage = 1;
        }
        if (nPage <= 0) nPage = 1;


        try
        {

            if (Request.QueryString[strLetter] != null)
            {
                strChar = Request.QueryString[strLetter].ToString();
                strCondition = " AND BizName like '" + strChar + "%'";
            }
        }
        catch
        {
            strChar = "";
        }

        if ((Session["logined_id"] != null) && (int.Parse(Session["logined_id"].ToString()) > 0))
        {
            if (Session["Trucker"] != "") nPermissions = int.Parse(Session["Trucker"].ToString());
        }
        else
            Response.Redirect("Login.aspx");

        if (!Page.IsPostBack)
        {
            LoadDropDownLocation();
            if (Session["LocationTrucker"] != null)
                ddLocationSearch.SelectedValue = Session["LocationTrucker"].ToString();
            if (nPermissions < 7)
                ddLocationSearch.Visible = false;
            if (nPermissions < 9)
                strCondition += " AND tbl_Trucker.LocationID in(" + Session["UserLocationIDs"].ToString() + ")";
            if (Session["LocationTrucker"] != null && Session["LocationTrucker"].ToString().ToLower() != "all")
            {
                if (Session["LocationTrucker"].ToString() != "")
                {
                    strCondition += " AND tbl_Trucker.LocationID=" + Session["LocationTrucker"].ToString();
                }
                else
                    strCondition += " AND tbl_Trucker.LocationID =0";
            }
            CommonFunctions.GetAllQueryString(Request, "", "action;ID", out strPartQuery);
            if (Request.QueryString["action"] == "delete" && nPermissions > 7)
            {
                Trucker obj = new Trucker();
                obj.ID = long.Parse(Request.QueryString["ID"].ToString());
                obj.Delete(GV.cn, GV.trans);
                Response.Redirect("Trucker.aspx" + strPartQuery);
            }
            if (Request.QueryString["action"] == "syndata" && nPermissions > 7)
            {
                if (int.Parse(Request.QueryString["ID"].ToString()) > 0)
                {
                    SynDataToTrucker(Request.QueryString["ID"].ToString());
                    Response.Redirect("Trucker.aspx" + strPartQuery);
                }
            }

            if (Request.QueryString["ID"] != null)
            {
                loadTrucker();
            }
            #region Build List
            int nNumOfPages = 0;

            DataTable dtList;
            BuildList(strCondition, NumOfItemsPerPage, nPage, out nNumOfPages, out dtList, null, null);
            if (nPage > nNumOfPages) nPage = 1;

            rptData.DataSource = dtList;
            rptData.DataBind();
            #endregion
            #region Build Pager
            CommonFunctions.BuildPager(Request, nNumOfPages, nPage, strPageID, ContainerPage, out strPager);
            #endregion
            CommonFunctions.BuildAphabetSearch(Request, ContainerPage, strLetter, strChar, strExcluded, out strAlphaBet);
        }

    }
    protected void loadTrucker()
    {
        Trucker obj = new Trucker();
        obj.ID = long.Parse(Request.QueryString["ID"]);
        obj.Load(GV.cn, GV.trans);
        txtBizName.Text = obj.BizName;
        txtFullName.Text = obj.FullName;
        txtInvoicingName.Text = obj.InvoicingName;
        txtAdd.Text = obj.Address;
        txtMST.Text = obj.MST;
        txtNote.Text = obj.Note;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        strError = "";
        strMess = "";
        Trucker obj = new Trucker();
        if (Request.QueryString["ID"] != null)
        {
            obj.ID = long.Parse(Request.QueryString["ID"]);
            obj.Load(GV.cn, GV.trans);
        }
        obj.BizName = txtBizName.Text.Trim();
        obj.LocationID = long.Parse(ddLocation.SelectedValue);
        obj.FullName = txtFullName.Text;
        obj.InvoicingName = txtInvoicingName.Text.Trim();
        obj.Address = txtAdd.Text.Trim();
        obj.MST = txtMST.Text.Trim();
        obj.Note = txtNote.Text.Trim();
        if (obj.BizName.Length == 0)
        {
            lblError.Text = "Biz Name không được để trống.";
            return;
        }
        obj.Save(GV.cn, GV.trans);
        //Update Trucker Pricing

        CommonFunctions.GetAllQueryString(Request, "", "action;ID", out strPartQuery);
        Response.Redirect("Trucker.aspx" + strPartQuery);
    }
    private void BuildList(string strCondition, int NumOfItemsPerPage, int PageNo, out int nNumOfPages, out DataTable dtList, MySqlConnection cn, MySqlTransaction trans)
    {
        DataSet ds = null;
        dtList = new DataTable();
        dtList.Columns.Add("Index");
        dtList.Columns.Add("BizName");
        dtList.Columns.Add("LocationName");
        dtList.Columns.Add("FullName");
        dtList.Columns.Add("InvoicingName");
        dtList.Columns.Add("Address");
        dtList.Columns.Add("MST");
        dtList.Columns.Add("Note");
        dtList.Columns.Add("Action");
        //Get List by SoIDs
        nNumOfPages = 0;
        Trucker obj = new Trucker();
        Trucker.GetList(strCondition, "BizName", NumOfItemsPerPage, PageNo, out nNumOfPages, out ds, GV.cn, GV.trans);

        string strAllQueryString = "";

        foreach (string strKey in Request.QueryString.AllKeys)
        {
            if (strKey != null)
            {
                if ((strKey.ToLower() != "action") && (strKey.ToLower() != "id"))
                    strAllQueryString = strAllQueryString + "&" + strKey + "=" + Request.QueryString[strKey].ToString();
            }
        }

        if (strAllQueryString.Length >= 1)
            strAllQueryString = strAllQueryString.Substring(1);

        if (ds != null)
        {
            int count = 0;
            if (Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "")
            {
                int pagenumber = 1;
                try
                {
                    pagenumber = int.Parse(Request.QueryString["page_number"]);
                    count = NumOfItemsPerPage * (pagenumber - 1);
                }
                catch { count = 0; }
            }
            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                count++;
                string strIndex = count.ToString();
                string BizName = dr["BizName"].ToString();
                string LocationName = dr["LocationName"].ToString();
                string FullName = dr["FullName"].ToString();
                string InvocingName = dr["InvoicingName"].ToString();
                string Address = dr["Address"].ToString();
                string MST = dr["MST"].ToString();
                string Note = dr["Note"].ToString();
                string strAction = "";
                if (nPermissions >= 3)
                    strAction = "<a href=\"Trucker.aspx?ID=" + dr["ID"].ToString() + ((Request.QueryString["page_number"] != null && Request.QueryString["page_number"].ToString() != "") ? "&page_number=" + Request.QueryString["page_number"].ToString() : "") +
                    ((Request.QueryString["letter"] != null && Request.QueryString["letter"].ToString() != "") ? "&letter=" + Request.QueryString["letter"].ToString() : "") +
                    "\">Edit</a>";
                if (nPermissions > 7)
                {
                    strAction += " - <a href=\"javascript:doDelete('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(BizName) + "')\">" + "Delete</a>";
                    strAction += " - <a href=\"javascript:doSynData('" + System.Web.HttpUtility.HtmlEncode(dr["ID"].ToString()) + "','" + System.Web.HttpUtility.HtmlEncode(BizName) + "')\">" + "Syn Data</a>";
                }

                string[] strValues = new string[] {  strIndex, 
                            BizName,
                            LocationName,
                            FullName,
                            InvocingName,
                            Address,
                            MST,
                            Note,
                            strAction };
                dtList.Rows.Add(strValues);
            }
        }
    }
    protected void LoadDropDownLocation()
    {
        string sqlCommand = "Select ID,Name From tbl_Location";
        DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        DataTable dt = ds.Tables[0];
        ddLocation.DataSource = dt;
        ddLocation.DataTextField = dt.Columns[1].ToString();
        ddLocation.DataValueField = dt.Columns[0].ToString();
        ddLocation.DataBind();
        if (Request.QueryString["ID"] != null)
        {
            Trucker obj = new Trucker();
            obj.ID = long.Parse(Request.QueryString["ID"].ToString());
            obj.Load(GV.cn, GV.trans);
            if (ddLocation.Items.FindByValue(obj.LocationID.ToString()) != null)
                ddLocation.SelectedValue = obj.LocationID.ToString();
        }
        //Location Search
        ddLocationSearch.Items.Add((new ListItem("Select Location", "All")));
        ddLocationSearch.AppendDataBoundItems = true;
        ddLocationSearch.DataSource = dt;
        ddLocationSearch.DataTextField = dt.Columns[1].ToString();
        ddLocationSearch.DataValueField = dt.Columns[0].ToString();
        ddLocationSearch.DataBind();
    }
    protected void ddLocationSearch_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["LocationTrucker"] = ddLocationSearch.SelectedValue;
        Response.Redirect("Trucker.aspx");
    }
    private void SynDataToTrucker(string truckerID)
    {

        Trucker obj = new Trucker();
        obj.ID = long.Parse(truckerID);
        obj.Load(GV.cn, GV.trans);
        string sqlCommand = "";
        sqlCommand = "Select   DISTINCT ExID,ToID  FROM tbl_TruckerPrice where ToID=" + obj.LocationID;
        DataSet ds = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string sql = "";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sqlCommand = "Select Id from tbl_TruckerPrice where ExID=" + dr["ExID"].ToString() +
                   " AND ToID=" + dr["ToID"].ToString() + " AND TruckerID=" + truckerID;
                DataSet dsCheck = DBModule.ExecuteQuery(sqlCommand, GV.cn, GV.trans);
                if (dsCheck.Tables[0].Rows.Count == 0)
                {
                    sql += "Insert Into tbl_TruckerPrice (TruckerID,ExID,ToID) values(" +
                    truckerID + "," + dr["ExID"].ToString() + "," + dr["ToID"].ToString() + ");";
                }
            }
            if (sql.Length > 0)
                DBModule.ExecuteNonQuery(sql, GV.cn, GV.trans);
        }
    }
}
